package com.lecture.springlecture.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.lecture.java8.excel.internationalization.EasyExcelI18n;
import com.lecture.java8.excel.internationalization.I18nAnalysisListener;
import com.lecture.java8.excel.internationalization.User;
import com.lecture.springlecture.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@RestController
public class DroolsController {

    private final MessageSource messageSource;

    public DroolsController(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
    @Autowired
    private TestService testService;

    @GetMapping("drools")
    public void drools() {
        testService.test();
    }


    @PostMapping("myRunner")
    public void myRunner() {
        Locale locale = new Locale("en_US");
        String message = messageSource.getMessage("user.name", null, locale);
        try {
            InputStream inputStream = new FileInputStream("D:\\用户.xlsx");

            List<User> userList = new ArrayList<>();
            EasyExcelI18n.read(inputStream, User.class, new I18nAnalysisListener<User>(messageSource, locale, User.class) {
                @Override
                public void invoke(User user, AnalysisContext context) {
                    userList.add(user);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {

                }
            }).sheet().doRead();
            System.out.println(userList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("importExcelTest")
    public void importExcelTest() {
        try {
            List<User> userList = new ArrayList<>();

            User u1 = new User();
            u1.setName("张三");
            u1.setAge(12);

            User u2 = new User();
            u2.setName("张三");
            u2.setAge(12);
            userList.add(u1);
            userList.add(u2);

            Locale locale = new Locale("zh_CN");
            OutputStream os = new FileOutputStream("D:\\test.xlsx");
            EasyExcelI18n.write(os,User.class,messageSource,locale).sheet("用户").doWrite(userList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
